package org.nerve.dir;

import org.nerve.dir.exception.ParserException;
import org.nerve.dir.exception.PickerException;
import org.nerve.dir.impl.ConsolePicker;
import org.nerve.dir.impl.WindowDirParser;

import java.io.IOException;

/**
 * 目录结构的通用解析总管
 * com.nerve.jiepu.forensicsystem.parser
 * Created by zengxm on 2015/7/2 0002.
 */
public class ParseManager extends AbstractFileReader {

	private long parseIndex;
	private long pickIndex;

	protected IPicker picker;
	protected IParser parser;

	public ParseManager() throws Exception {
		super();
	}

	public ParseManager(String fileLoc)throws Exception{
		this(fileLoc, null, null);
	}

	/**
	 * @param fileLoc   需要解析的文件地址
	 * @param parser    解析器
	 * @param picker    采集器
	 * @throws Exception
	 */
	public ParseManager(String fileLoc, IParser parser, IPicker picker) throws Exception{
		super();

		init(fileLoc, parser, picker);
	}

	public void init(String fileLoc, IParser parser, IPicker picker) throws IOException {
		if(picker == null){
			logger.debug("Picker is null， use ConsolePicker ...");
			this.picker = new ConsolePicker();
		}else
			this.picker = picker;

		this.filePath = fileLoc;
		setParser(parser);
	}

	/**
	 * 目前都是返回true，即一直读取到文件最后
	 * @param line
	 * @return
	 */
	@Override
	protected boolean onData(String line) {
		try{
			Content entity = parser.parse(line);
			if(entity != null ){
				parseIndex ++;
				if(picker!=null){
					picker.onData(entity);

					//如果入库成功，pickIndex就加一
					pickIndex++;
				}
			}
		}catch (ParserException e){
			logger.error("parserException", e);
		}catch (PickerException e){
			logger.error("pickerException", e);
		}catch (Exception e){
			logger.error("-->", e);
		}
		return true;
	}

	@Override
	protected void onEnd() {
		logger.info("work Done！ parse "+parseIndex+", pick "+pickIndex);
	}

	public IPicker getPicker() {
		return picker;
	}

	/**
	 * 设置Content采集器，通常ContentPicker是用来保存解析到的Content
	 * @param picker
	 */
	public void setPicker(IPicker picker) {
		this.picker = picker;
	}

	public IParser getParser() {
		return parser;
	}

	/**
	 * 设置解析器，通常解析器是用于从字节数据中解析出对应的Content对象
	 * @param parser
	 */
	public void setParser(IParser parser) throws IOException {
		if(parser!= null){
			this.parser = parser;
			logger.info("using parser ["+parser.getClass().getName()+", name="+parser.getName()+"]");
		}else{
			logger.debug("Parser is null， use "+ WindowDirParser.class.getName()+"...");
			this.parser = new WindowDirParser();
		}

		setEncoding(this.parser.getEncoding());
	}

	public long getParseCount() {
		return parseIndex;
	}

	public long getPickCount() {
		return pickIndex;
	}
}
